<?php

class Core_Util {

    static public function getConfig($key) {
        $config_file = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini');
        $configs = $config_file->get("production")->toArray();
        return $configs[$key];
    }

    static public function getAllServices() {
        return array(
            "dunnage" => "Dunnage",
            "tally" => "Tally",
            "cargo" => "Cargo",
        );
    }

    static public function getAllMaterials() {
        return array(
            "dunnage" => "Dunnage Material",
            "tally" => "Tally Material",
        );
    }

    static public function getAllUnit() {
        return array(
            'M2' => 'M2',
            'K2' => 'K2',
            'L2' => 'L2',
        );
    }

    static public function getAdminActiveMenu($action, $params) {
        $service_type = NULL;
        if (isset($params['type'])) {
            $service_type = $params['type'];
        }
        $menus = array(
            'index' => array('active_menu' => 'home', 'active_submenu' => NULL),
            'service-content' => array('active_menu' => 'service', 'active_submenu' => $service_type),
            'ports' => array('active_menu' => 'ports', 'active_submenu' => 'list_port'),
            'editport' => array('active_menu' => 'ports', 'active_submenu' => 'list_port'),
            'newport' => array('active_menu' => 'ports', 'active_submenu' => 'list_port'),
            'buoys' => array('active_menu' => 'ports', 'active_submenu' => 'list_buoy'),
            'newbuoy' => array('active_menu' => 'ports', 'active_submenu' => 'list_buoy'),
            'editbuoy' => array('active_menu' => 'ports', 'active_submenu' => 'list_buoy'),
            'users' => array('active_menu' => 'users', 'active_submenu' => 'list_user'),
            'newuser' => array('active_menu' => 'users', 'active_submenu' => 'new_user'),
            'edituser' => array('active_menu' => 'users', 'active_submenu' => 'list_user'),
            'emailsetting' => array('active_menu' => 'emailsetting', 'active_submenu' => NULL),
            'about' => array('active_menu' => 'about', 'active_submenu' => null),
            'services' => array('active_menu' => 'services', 'active_submenu' => 'list_services'),
            'new-service' => array('active_menu' => 'services', 'active_submenu' => 'list_services'),
            'edit-service' => array('active_menu' => 'services', 'active_submenu' => 'list_services'),
            "newdunnagematerial" => array('active_menu' => 'material', 'active_submenu' => 'dunnage'),
            "editdunnagematerial" => array('active_menu' => 'material', 'active_submenu' => 'dunnage'),
            "newtallyservice" => array('active_menu' => 'material', 'active_submenu' => 'tally'),
            "edittallyservice" => array('active_menu' => 'material', 'active_submenu' => 'tally'),
            'purposes' => array('active_menu' => 'purposes', 'active_submenu' => null),
            'newpurpose' => array('active_menu' => 'purposes', 'active_submenu' => null),
            'editpurpose' => array('active_menu' => 'purposes', 'active_submenu' => null),
            'signerstatus' => array('active_menu' => 'signerstatus', 'active_submenu' => null),
            'newsignerstatus' => array('active_menu' => 'signerstatus', 'active_submenu' => null),
            'editsignerstatus' => array('active_menu' => 'signerstatus', 'active_submenu' => null),
            'tide-ports' => array('active_menu' => 'tide-ports', 'active_submenu' => 'tide-ports'),
            'new-tide-port' => array('active_menu' => 'tide-ports', 'active_submenu' => 'tide-ports'),
            'new-main-port' => array('active_menu' => 'main-ports', 'active_submenu' => 'main-ports'),
            'main-ports' => array('active_menu' => 'main-ports', 'active_submenu' => 'main-ports'),
            'update-tide-port' => array('active_menu' => 'tide-ports', 'active_submenu' => 'tide-ports')
        );
        return $menus[$action];
    }

    static public function getCountryList() {
        $content = file_get_contents(APPLICATION_PATH . DIRECTORY_SEPARATOR . 'include' . DIRECTORY_SEPARATOR . 'countries');
        $content = nl2br($content);
        $contries = explode("<br />", $content);
        foreach ($contries as &$country) {
            $country = trim($country);
        }
        return $contries;
    }

    static public function getRoleList() {
        return array(
            'Principal',
            'Input Data',
            'Admin'
        );
    }

    static public function hasAccess($transId) {
        if (!$transId) {
            return false;
        }
        $db = Zend_Registry::get('db');
        $session = Zend_Registry::get("session");
        $userId = isset($session->user) ? $session->user->id : null;
        $role = Core_Util::getRole();

        switch (strtolower($role)) {
            case Core_Role::ROLE_PRINCIPAL:
                $query = "select * from transactions t
                          left join general_information g on g.id = t.general_information_id
                          where t.id = {$transId} and g.customer_id = {$userId}";
                $result = $db->fetchAll($query);
                if ($result && is_array($result) && count($result) > 0) {
                    return true;
                } else {
                    return false;
                }
                break;
            case Core_Role::ROLE_INPUT:
                $query = "select * from transactions t
                          where t.id = {$transId} and t.input_user = {$userId}";
                $result = $db->fetchAll($query);
                if ($result && is_array($result) && count($result) > 0) {
                    return true;
                } else {
                    return false;
                }

                break;
            case Core_Role::ROLE_ADMIN:
                return true;
                break;
            case Core_Role::ROLE_GUEST:
            default:
                return false;
        }
    }

    static public function isDebugMode() {
        return APPLICATION_ENV == 'development';
    }

    static public function rememberMe() {
        $max_time = self::getConfig("remember_me_time");
        Zend_Session::rememberMe($max_time);
    }

    static public function getRole() {
        $session = Zend_Registry::get("session");
        $user = $session->user;
        if ($user) {
            return $user["role"];
        } else {
            return null;
        }
    }

    public static function renderDate($time) {
        if (!empty($time)) {
            echo date(DATE_FORMAT, $time);
        }
    }

    public static function getTimestamp($date, $format = '!d/m/Y') {
        if (!empty($date)) {
            $time = Datetime::createFromFormat($format, $date);
            return $time->getTimestamp();
        }
        return NULL;
    }

    public static function convert_number_to_words($number) {

        $hyphen = ' ';
        $conjunction = '  ';
        $separator = ', ';
        $negative = 'negative ';
        $decimal = ' and ';
        $dictionary = array(
            0 => 'zero',
            1 => 'one',
            2 => 'two',
            3 => 'three',
            4 => 'four',
            5 => 'five',
            6 => 'six',
            7 => 'seven',
            8 => 'eight',
            9 => 'nine',
            10 => 'ten',
            11 => 'eleven',
            12 => 'twelve',
            13 => 'thirteen',
            14 => 'fourteen',
            15 => 'fifteen',
            16 => 'sixteen',
            17 => 'seventeen',
            18 => 'eighteen',
            19 => 'nineteen',
            20 => 'twenty',
            30 => 'thirty',
            40 => 'fourty',
            50 => 'fifty',
            60 => 'sixty',
            70 => 'seventy',
            80 => 'eighty',
            90 => 'ninety',
            100 => 'hundred',
            1000 => 'thousand',
            1000000 => 'million',
            1000000000 => 'billion',
            1000000000000 => 'trillion',
            1000000000000000 => 'quadrillion',
            1000000000000000000 => 'quintillion'
        );

        if (!is_numeric($number)) {
            return false;
        }

        if (($number >= 0 && (int) $number < 0) || (int) $number < 0 - PHP_INT_MAX) {
            // overflow
            trigger_error(
                    'convert_number_to_words only accepts numbers between -' . PHP_INT_MAX . ' and ' . PHP_INT_MAX, E_USER_WARNING
            );
            return false;
        }

        if ($number < 0) {
            return $negative . self::convert_number_to_words(abs($number));
        }

        $string = $fraction = null;

        if (strpos($number, '.') !== false) {
            list($number, $fraction) = explode('.', $number);
        }

        switch (true) {
            case $number < 21:
                $string = $dictionary[$number];
                break;
            case $number < 100:
                $tens = ((int) ($number / 10)) * 10;
                $units = $number % 10;
                $string = $dictionary[$tens];
                if ($units) {
                    $string .= $hyphen . $dictionary[$units];
                }
                break;
            case $number < 1000:
                $hundreds = $number / 100;
                $remainder = $number % 100;
                $string = $dictionary[$hundreds] . ' ' . $dictionary[100];
                if ($remainder) {
                    $string .= $conjunction . self::convert_number_to_words($remainder);
                }
                break;
            default:
                $baseUnit = pow(1000, floor(log($number, 1000)));
                $numBaseUnits = (int) ($number / $baseUnit);
                $remainder = $number % $baseUnit;
                $string = self::convert_number_to_words($numBaseUnits) . ' ' . $dictionary[$baseUnit];
                if ($remainder) {
                    $string .= $remainder < 100 ? $conjunction : $separator;
                    $string .= self::convert_number_to_words($remainder);
                }
                break;
        }

        if (null !== $fraction && is_numeric($fraction)) {
            $string .= $decimal;
//            $words = array();
//            Zend_Debug::dump($fraction);die();
//            foreach (str_split((string) $fraction) as $number) {
//                $words[] = $dictionary[$number];
//            }
//            $string .= implode(' ', $words);
            if (strlen($fraction) < 2) {
                $fraction *= 10;
            }
            $fraction = intval($fraction);
            $string .= self::convert_number_to_words($fraction) . ' cents';
        }

        return $string;
    }

    public static function displayCurrrency($value, $symbol = '$') {
        $currency = new Zend_Currency(
                array(
            'value' => $value,
            'symbol' => $symbol,
                )
        );
        return $currency;
    }

    public static function isAdmin() {
        $session = Zend_Registry::get("session");
        if ($session && isset($session->user)) {
            $user = $session->user;
            if ($user) {
                if ($user->role) {
                    switch (strtolower($user->role)) {
                        case strtolower(Core_Role::ROLE_ADMIN):
                            return true;
                        default:
                            return false;
                    }
                }
                return false;
            }
            return false;
        }
        return false;
    }

    public static function hasAccessNewService() {
        $session = Zend_Registry::get("session");
        if ($session && isset($session->user)) {
            $user = $session->user;
            if ($user) {
                if ($user->role) {
                    switch (strtolower($user->role)) {
                        case strtolower(Core_Role::ROLE_INPUT):
                        case strtolower(Core_Role::ROLE_ADMIN):
                            return true;
                        default:
                            return false;
                    }
                }
                return false;
            }
            return false;
        }
        return false;
    }

    public static function hasAccessViewService($service_id) {
        $session = Zend_Registry::get("session");
        if ($session && isset($session->user)) {
            $user = $session->user;
            if ($user) {
                if ($user->role) {
                    switch (strtolower($user->role)) {
                        case strtolower(Core_Role::ROLE_INPUT):
                        case strtolower(Core_Role::ROLE_ADMIN):
                            return true;
                        case strtolower(Core_Role::ROLE_PRINCIPAL):
                            $db = Zend_Registry::get("db");
                            if ($db) {
                                $query = "select id from general_information where id = {$service_id} and customer = {$user->id}";
                                $result = $db->fetchAll($query);

                                if (!$result || (is_array($result) && count($result) == 0)) {
                                    return false;
                                } else {
                                    return true;
                                }
                            }
                            return false;
                        default:
                            return false;
                    }
                }
                return false;
            }
            return false;
        }
        return false;
    }

    public static function scaleImage($src_file, $des_path, $percentage = 75) {
        $token = explode(".", $src_file);
        if (is_array($token) && count($token) > 1) {
            $ext = end($token);
            switch ($ext) {
                case "png":
                case "PNG":
                    imagepng(imagecreatefrompng($src_file), $des_path, 5);
                    break;
                case "gif":
                    imagegif(imagecreatefromgif($src_file), $des_path);
                    break;
                case 'jpg':
                case 'jpeg':
                    imagejpeg(imagecreatefromjpeg($src_file), $des_path, $percentage);
                    break;
            }
        }
        return false;
    }

    public static function log($exception) {
        $writer = new Zend_Log_Writer_Stream(LOG_PATH . '/epac.log');
        $logger = new Zend_Log($writer);
        $logger->log($exception->getMessage(), 0);
    }

    public static function getMainPortRegions() {
        return array(
            'Binh Tri',
            'Cai Lan',
            'Cam Pha',
            'Can Tho',
            'Chan May',
            'Cua Lo',
            'Da Nang',
            'Go Dau',
            'Go Gia',
            'Hai Phong',
            'Ho Chi Minh',
            'Nghi Son',
            'Nha Trang',
            'Phu My - Cai Mep',
            'Quy Nhon',
            'Vietso and PTSC',
            'Vung Ang'
        );
    }

    public static function getTidePortRegions() {
        return array(
            'Binh Tri',
            'Cai Lan',
            'Cam Pha',
            'Can Tho',
            'Chan May',
            'Cua Lo',
            'Da Nang',
            'Go Dau',
            'Go Gia',
            'Hai Phong',
            'Ho Chi Minh',
            'Nghi Son',
            'Nha Trang',
            'Phu My - Cai Mep',
            'Quy Nhon',
            'Vietso and PTSC',
            'Vung Ang'
        );
    }
    
    public static function formatNumber($number) {
        return number_format($number, 0, '.', ',');
    }

}

?>
